package com.meitianhui.convenitenbuy.module.wallet.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.module.wallet.contract.WalletScanningContract;
import com.meitianhui.convenitenbuy.module.wallet.di.DaggerWalletComponent;
import com.meitianhui.convenitenbuy.module.wallet.di.WalletModule;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.ScanningBean;
import com.meitianhui.convenitenbuy.module.wallet.model.StoreInfoBean;
import com.meitianhui.convenitenbuy.module.wallet.presenter.WalletScanningPresenter;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxTimerUtils;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.PasswordDialog;
import com.meitianhui.convenitenbuy.widget.dialog.SettingStoreDialog;
import com.meitianhui.convenitenbuy.zxing.activity.CaptureActivity;

import java.math.BigDecimal;

import javax.inject.Inject;

/**
 * Created by Administrator on 2017/11/15.
 */

public class WalletScanningActivity extends CaptureActivity implements WalletScanningContract.View, PasswordDialog.OnDialogPsdCompleteListener {

    private TextView mTvStatus;
    private RxTimerUtils mRx;
    private RxTimerUtils.IRxNext failNext;
    private Gson gson;
    private LinearLayout mLlScan;
    private LinearLayout mLlConfirm;
    private TextView mTvType;
    private TextView mTvValue;
    private Button mBtn;
    private ScanningBean mBean;
    private PasswordDialog passwordDialog;
    @Inject
    WalletScanningPresenter presenter;
    private SettingStoreDialog dialog;

    @Override
    protected void initId() {
        super.initId();
        mLlScan = getViewById(R.id.ll_wallet_scanning_scan);
        mLlConfirm = getViewById(R.id.ll_wallet_scanning_pay);
        mTvStatus = getViewById(R.id.tv_wallet_scanning_status);
        mTvType = getViewById(R.id.tv_wallet_scanning_type);
        mTvValue = getViewById(R.id.tv_wallet_scanning_value);
        mBtn = getViewById(R.id.btn_wallet_scanning_confirm);
    }

    @Override
    protected int setView() {
        return R.layout.wallet_scanning_container;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        DaggerWalletComponent.builder().appComponent(App.getInstance().getAppComponent()).walletModule(new WalletModule(this)).build().inject(this);
        mRx = new RxTimerUtils();
        failNext = new RxTimerUtils.IRxNext() {
            @Override
            public void doNext(long number) {
                mTvStatus.setText("");
                setReCapture();
            }
        };
        gson = new Gson();
        RxUtils.bindEvents(mBtn, this);
    }

    @Override
    protected void receiveResult(String resultString) {
        if (TextUtils.isEmpty(resultString)) {
            mTvStatus.setText(getString(R.string.wallet_scanning_fail));
            mRx.timer(8000, failNext);
            return;
        }

        mTvStatus.setText(getString(R.string.wallet_scanning_waiting));
        if (resultString.startsWith("{") && resultString.endsWith("}")) {
            mBean = gson.fromJson(resultString, ScanningBean.class);
            presenter.verifyCode(mBean);
        } else {
            presenter.getStore(resultString);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRx.cancel();
    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void verifyCodeResult(int result, ScanningBean bean, String msg) {
        switch (result) {
            case -1:
                mLlConfirm.setVisibility(View.GONE);
                mLlScan.setVisibility(View.VISIBLE);
                mTvStatus.setText(getString(R.string.wallet_scanning_invalid));
                mRx.timer(8000, failNext);
                break;
            case 0:
                mLlConfirm.setVisibility(View.GONE);
                mLlScan.setVisibility(View.VISIBLE);
                mTvStatus.setText(getString(R.string.wallet_scanning_wrong));
                mRx.timer(8000, failNext);
                break;
            case 1:
                verifyCodeSuccess(bean);
                break;

        }
    }

    public void verifyCodeSuccess(ScanningBean bean) {
        mLlScan.setVisibility(View.GONE);
        mLlConfirm.setVisibility(View.VISIBLE);
        if (TextUtils.equals(bean.getType(), "r") || TextUtils.equals(bean.getType(), "R")) {
            BigDecimal number = new BigDecimal(bean.getAmount());//判断余额是否足够
            if (number.compareTo(new BigDecimal(InfoProvider.getUserAsset(App.getInstance()).getCash_balance())) == 1) {
                showMessageDialog();
                mLlConfirm.setVisibility(View.GONE);
                return;
            }
            mBtn.setText(getResources().getString(R.string.wallet_scanning_confirm_pay));
            mTvType.setText(getResources().getString(R.string.wallet_scanning_confirm_pay_value));
        } else if (TextUtils.equals(bean.getType(), "P") || TextUtils.equals(bean.getType(), "p")) {
            mBtn.setText(getResources().getString(R.string.wallet_scanning_confirm_receive));
            mTvType.setText(getResources().getString(R.string.wallet_scanning_confirm_receive_value));
        }
        mTvValue.setText(bean.getAmount() + getString(R.string.wallet_packet_unit_change));
    }

    private void showMessageDialog() {
        dialog = new SettingStoreDialog(this, new SettingStoreDialog.AlertDialogListener() {
            @Override
            public void onConfirmClick() {
                dialog.dismiss();
                finish();
            }

            @Override
            public void onCancelClick() {

            }
        });
        dialog.show();
        dialog.showCancelBtn(false);
        dialog.setConfirmBtnText("确定");
        dialog.setDialogTitle("余额不足");
    }

    @Override
    public void call(View v) {
        super.call(v);
        if (v.getId() == R.id.btn_wallet_scanning_confirm) {
            clickConfirm();
        }
    }

    private void clickConfirm() {
        UserToken userToken = InfoProvider.getUserToken(App.getInstance());
        if (TextUtils.equals(mBean.getType(), "r") || TextUtils.equals(mBean.getType(), "R")) {
            if (userToken.getSmall_direct_flag().equals("N") && userToken.getPayment_password_flag().equals("Y")) {
                showPasswordDialog();
            } else if (userToken.getSmall_direct_flag().equals("Y") &&
                    Float.parseFloat(mBean.getAmount().trim()) > Constants.SMALL_AMOUNT && userToken.getPayment_password_flag().equals("Y")) {
                showPasswordDialog();
            } else {
                mBtn.setEnabled(false);
                presenter.payForOrder(mBean);
            }
        } else if (TextUtils.equals(mBean.getType(), "P") || TextUtils.equals(mBean.getType(), "p")) {
            mBtn.setEnabled(false);
            presenter.receiptByOrder(mBean);
        }

    }

    private void showPasswordDialog() {
        passwordDialog = new PasswordDialog(this, R.layout.dialog_payment_pwd);
        passwordDialog.setOnDialogPsdCompareListener(this);
        passwordDialog.show();
//        passwordDialog.setPsdDescription(getString(R.string.dialog_password_function));
        passwordDialog.setPsdContent(mBean.getAmount());
    }

    @Override
    public void onPasswordCorrect(PasswordDialog dialog) {
        mBtn.setEnabled(false);
        passwordDialog.dismiss();
        presenter.payForOrder(mBean);
    }

    @Override
    public void onPasswordError(PasswordDialog dialog, String msg) {
        TipUtils.showToast(App.getInstance(), getString(R.string.wallet_payment_setting_password_wrong));
        passwordDialog.clearInput();
    }

    @Override
    public void paymentResult(boolean result, String msg) {
        if (!result) {
            if (msg != null)
                TipUtils.showToast(App.getInstance(), msg);
            mBtn.setEnabled(true);
        } else {
            TipUtils.showToast(App.getInstance(), getString(R.string.wallet_change_recharge_success), 1);
            RxBus.get().post(new PayResultBean(Constants.PAY_RESULT_SUCCESS));
            finish();
        }
    }

    @Override
    public void receiptResult(boolean result, String msg) {
        if (result) {
            TipUtils.showToast(App.getInstance(), getString(R.string.wallet_scanning_confirm_receive_success));
            RxBus.get().post(new PayResultBean(Constants.PAY_RESULT_SUCCESS));
            finish();
        } else {
            TipUtils.showToast(App.getInstance(), msg);
            mBtn.setEnabled(true);
        }
    }

    @Override
    public void getStoreBack(StoreInfoBean bean,String storeId) {
        Intent intent = new Intent(this, WalletScanningStoreActivity.class);
        intent.putExtra(Constants.ARGUMENT, bean);
        intent.putExtra("storeId", storeId);
        startActivity(intent);
        finish();
    }


}
